<?php

namespace app\api\model\project;

use addons\epay\library\Service;
use app\admin\model\Crontab;
use app\api\model\project\ProjectOrder as ProjectOrderModel;
use app\api\model\User;
use think\Db;
use think\Log;
use think\Model;
use Yansongda\Pay\Pay;


class ProjectOrder extends Model
{





    // 表名
    protected $name = 'project_order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];




    public function add($user_id,$staff_id,$project_arr,$name,$mobile,$remark,$parent_order_no)
    {
        Db::startTrans();
        try {
            $staff_info = ProjectStaff::where(['id'=>$staff_id])->field('user_id')->find();

            $order_model = new ProjectOrder();

            $order_data = [];

            foreach ($project_arr as $k=>$v){
                $category = ProjectCategory::get($v['category_id']);
                $service_start = $v['service_start_date'].' '.$v['service_start_time'];
                $service_end = $v['service_end_date'].' '.$v['service_end_time'];

                $order_data[] = [
                    'user_id'=>$user_id,
                    'staff_id'=>$staff_id,
                    'parent_order_no'=>$parent_order_no,
                    'staff_user_id'=>$staff_info['user_id'],
                    'apply_id'=>$v['id'],
                    'order_no'=>$this->order_no(),
                    'name'=>$name,
                    'mobile'=>$mobile,
                    'remark'=>$remark,
                    'order_status_name'=>'待支付',
                    'service_start_date'=>$v['service_start_date'],
                    'service_end_date'=>$v['service_end_date'],
                    'service_start_time'=>$v['service_start_time'],
                    'service_end_time'=>$v['service_end_time'],
                    'service_start'=>$service_start,
                    'service_end'=>$service_end,
                    'service_start_timestamp'=>strtotime($service_start),
                    'service_end_timestamp'=>strtotime($service_end),
                    'num'=>$v['num'],
                    'project_name'=>$v['name'],
                    'project_category_name'=>$category['name'],
                    'price'=>$v['price'],
                    'pay_price'=>$v['price']*$v['num'],
                ];
            }

            $res = $order_model->saveAll($order_data);

            $cron = new Crontab();
            $cron_list = [];

            $close_time = \app\common\model\Config::get(['name'=>'close_time'])->value;
            $end_time_timestamp = time()+60*$close_time;
            foreach ($res  as $k=>$v){
                $cron_list[] = [
                    'type'=>'url',
                    'title'=>'关闭服务订单,订单id:'.$v['order_id'],
                    'content'=>request()->domain().'/api/projectorder/cancel?order_id='.$v['order_id'],
                    'schedule'=>schedule($end_time_timestamp),
                    'maximums'=>1,
                    'begintime'=>time(),
                    'endtime'=>$end_time_timestamp,
                    'status'=>'normal'
                ];
            }
            $cron->saveAll($cron_list);
            Db::commit();
            return true;
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw new \Exception($e->getMessage().'-'.$e->getLine());
        }

    }

    //单个单支付回调
    public function notify($out_trade_no,$paytype)
    {
        $order = ProjectOrder::get(['order_no' => $out_trade_no]);
        dump($order);die;
        if ($order->pay_status==0){
            $order->pay_type = $paytype;
            $order->order_status = 1;
            $order->order_status_name = '待服务';
            $order->pay_status = 1;
            $order->pay_time = time();
            $order->save();
            ProjectApply::where(['id'=>$order->apply_id])->setInc('order_money',$order->pay_price);
            ProjectApply::where(['id'=>$order->apply_id])->setInc('order_num',1);
            User::where(['id'=>$order->user_id])->setInc('order_money',$order->pay_price);
            User::where(['id'=>$order->user_id])->setInc('order_num',1);
            \app\common\model\User::upgradelevel($order->user_id);
        }
        return true;
    }

    //合单支付回调
    public function notifyx($parent_order_no,$paytype)
    {
        $order_list = ProjectOrder::where(['parent_order_no' => $parent_order_no])->select();
        foreach ($order_list as $k=>$v){
            $order = ProjectOrder::get(['order_no' => $v['order_no']]);
            if ($order->pay_status==0){
                $order->pay_type = $paytype;
                $order->order_status = 1;
                $order->order_status_name = '待服务';
                $order->pay_status = 1;
                $order->pay_time = time();
                $order->save();
                ProjectApply::where(['id'=>$order->apply_id])->setInc('order_money',$order->pay_price);
                ProjectApply::where(['id'=>$order->apply_id])->setInc('order_num',1);
                User::where(['id'=>$order->user_id])->setInc('order_money',$order->pay_price);
                User::where(['id'=>$order->user_id])->setInc('order_num',1);
                \app\common\model\User::upgradelevel($order->user_id);
            }

        }
        return true;
    }


    public function order_no(){
        $order_no = null;
        while (true) {
            $order_no = date('YmdHis') . mt_rand(1000, 9999);
            $exist_order_no = ProjectOrder::get(['order_no' => $order_no]);
            if (!$exist_order_no) {
                break;
            }
        }
        return $order_no;
    }


    //取消
    public function cancel($order_id,$user_id)
    {

        $order_info = ProjectOrderModel::get(['order_id'=>$order_id,'user_id'=>$user_id]);

        if (!$order_info) throw new \Exception('订单不存在');

        if ($order_info->order_status==-1)throw new \Exception('已取消');

        $order_info->order_status = -1;

        $order_info->order_status_name = '已取消';

        $order_info->is_cancel = 1;

        $order_info->cancel_time = time();

        if ($order_info->save()){

            return true;
        } else {
            throw new \Exception('取消失败');
        }
    }


    //退单
    public function refund($order_id,$user_id)
    {
        $info = ProjectOrderModel::get(['order_id'=>$order_id,'user_id'=>$user_id]);

        if (!$info)throw new \Exception('订单不存在');
        if ($info->pay_status==0)throw new \Exception('未支付');
        Db::startTrans();
        try {

            $start = $info->service_start_timestamp;
            $date = date('Y-m-d',time());
            $refund_price = $info->pay_price;

            if ($start-time()<3*86400&&$start-time()>86400){
                //提前三天推单,扣20%反用户80%
                $refund_price = $info->pay_price*0.8;
            } elseif ($start-time()<86400&&$date!=$info->service_start_date){
                //提前一天推单,扣50%反用户50%
                $refund_price = $info->pay_price*0.5;
            } elseif ($date==$info->service_start_date){
                $refund_price = 0;
            }
            if ($refund_price){
                $res = $this->refundoperate($info->order_no, 'wechat',$refund_price);
                if (!$res){
                    Db::rollback();
                    throw new \Exception('退款失败');
                }
            }
            $info->order_status = -1;

            $info->order_status_name = '已取消';

            $info->is_refund = 1;

            if ($info->save()){
                Db::commit();
                return true;
            } else {
                Db::rollback();
                throw new \Exception('退单失败');
            }


        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw new \Exception($e->getMessage().'-'.$e->getLine());
        }

    }

    /**
     * 退款操作
     */
    public function refundoperate($order_sn, $paytype, $payamount)
    {
        $config = Service::getConfig($paytype);
        try {
            //$order = Order::getByOrderSn($order_sn);

            $response = Pay::wechat($config)->refund([
                'type'          => 'app',
                'out_trade_no'  => $order_sn,
                'out_refund_no' => time(),
                'total_fee'     => $payamount * 100,
                'refund_fee'    => $payamount * 100
            ]);

            if (!$response['result_code'] || $response['result_code'] != 'SUCCESS') {
                throw new \Exception(($response['err_code'] ?? '') . ':' . ($response['err_code_des'] ?? '未知退款错误'));
            }

        } catch (\Exception $e) {
            Log::write("[{$order_sn}]同步退款失败，失败原因：" . $e->getMessage(), 'refund');
            throw new \Exception("同步退款失败，失败原因：" . $e->getMessage());

        }

        return true;
    }

}
